package com.deuwise.job.customquartz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.deuwise.common.exception.DeuWiseException;
import com.deuwise.common.utils.EnumErrorCode;
import com.deuwise.common.utils.SpringContextHolder;
import com.deuwise.job.customquartz.base.JobRun;
import com.deuwise.job.customquartz.base.JobRunLogHelper;
import com.deuwise.job.entity.JobRunLogDo;
import com.deuwise.system.entity.SysRole;
import com.deuwise.system.entity.SysUser;
import com.deuwise.system.entity.SysUserRole;
import com.deuwise.system.entity.TokenVO;
import com.deuwise.system.service.SysRoleService;
import com.deuwise.system.service.SysUserRoleService;
import com.deuwise.system.service.SysUserService;
import com.github.kevinsawicki.http.HttpRequest;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.management.relation.Role;
import javax.management.relation.RoleInfo;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenwenchao
 * @date 2018/5/07 Description:
 * <p>
 * 定时同步用户信息(承压院统一用户接口)
 */

public class JobSysUserInfo implements Job,JobRun {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //添加执行日志
        System.out.println("JobSysUserInfo：启动任务=======================");
        /*
         * 添加运行日志
         *
         * */
        JobRunLogHelper jobRunLogHelper= SpringContextHolder.getBean(JobRunLogHelper.class);
        JobRunLogDo jobRunLogDo=new JobRunLogDo();
        jobRunLogHelper.getBaseRunLog(context,jobRunLogDo, this.getClass());

    }

    @Override
    public void run() {
        // 当前页
        int pageIndex = 1;
        // 每页大小，默认50
        int pageSize = 50;
        // 默认20页，即1000员工
        int pageNum = 20;

        // 获取tocken
        String tocken = getTokenRequest();
        if(StringUtils.isNotBlank(tocken)){
            for(int i = pageIndex; i <= pageNum; i++) {
                boolean isSuccess = sysUserInfoSync(tocken, i, pageSize);
                if(!isSuccess){
                    // 为false,退出同步
                    break;
                }
            }
        }

        System.out.println("JobSysUserInfo：执行完毕=======================");

    }

    /**
     * 获取token
     * @return
     */
    public String getTokenRequest(){

        Environment env=SpringContextHolder.getBean(Environment.class);
        String restUrl= env.getProperty("unifiedUser.restUrl");
        String loginName= env.getProperty("unifiedUser.loginName");
        String password= env.getProperty("unifiedUser.password");
        String systemCode= env.getProperty("unifiedUser.systemCode");

        //登录，返回token
        String token = null;
        JSONObject payload = new JSONObject();
        payload.put("password", password);
        payload.put("loginName", loginName);
        payload.put("systemCode", systemCode);

        try {
            //  调用后台管理登录接口，获取token
            HttpRequest httpRequest = HttpRequest.get(restUrl + "/system/rest/gettoken", payload, false);
            boolean falg = httpRequest.code() == 200;
            if (falg) {
                JSONObject jsonObject = JSONObject.parseObject(httpRequest.body());
                if(null != jsonObject.get("data")){
                    JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
                    token = data.get("token").toString();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new DeuWiseException(EnumErrorCode.apiAuthorizationInvalid.getCodeStr());
        }
        return token;
    }

    /**
     * 统一用户信息同步
     * @param token
     * @param pageIndex 当前页，从1开始
     * @param pageSize 每页大小，不超过100
     */
    public boolean sysUserInfoSync(String token, int pageIndex, int pageSize){
        SysUserService sysUserService = SpringContextHolder.getBean(SysUserService.class);
        Environment env=SpringContextHolder.getBean(Environment.class);
        String restUrl= env.getProperty("unifiedUser.restUrl");
        String systemCode= env.getProperty("unifiedUser.systemCode");
        String deptId= env.getProperty("unifiedUser.deptId");
        String roleId= env.getProperty("unifiedUser.roleId");
        String granularity= "ALL";

        int pageCount = 1;

        //登录，返回token
        JSONObject payload = new JSONObject();
        payload.put("token", token);
        payload.put("granularity", granularity);
        payload.put("systemCode", systemCode);
        payload.put("pageIndex", pageIndex);
        payload.put("pageSize", pageSize);

        try {
            //  调用后台管理登录接口，获取token
            HttpRequest httpRequest = HttpRequest.get(restUrl + "/system/rest/users", payload, false);
            httpRequest.send(payload.toJSONString());
            boolean falg = httpRequest.code() == 200;
            List<String> userIds = new ArrayList<>();
            List<SysUser> userList = new ArrayList<>();
            List<SysUserRole> userRoleList = new ArrayList<>();
            List<SysRole> sysRoleList = new ArrayList<>();
            if (falg) {
                JSONObject jsonObject = JSONObject.parseObject(httpRequest.body());
                if(null != jsonObject.get("data")){
                    JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
                    // 总页码数
                    pageCount = JSONObject.parseObject(data.getString("pager")).getInteger("pageCount");


                    JSONArray dataArray = data.getJSONArray("data");
                    if(dataArray!=null&& dataArray.size()>0){
                        for(int i = 0; i< dataArray.size(); i++) {
                            JSONObject object = dataArray.getJSONObject(i);

                            // 查询用户是否存在
                            SysUser sysUser = sysUserService.queryByUserName(object.getString("workNum"));
                            if(null == sysUser){
                                sysUser = new SysUser();
                                sysUser.setId(object.getString("id"));
                            }

                            sysUser.setName(object.getString("userName"));
                            // 员工号
                            sysUser.setUsername(object.getString("workNum"));
                            sysUser.setEmail(object.getString("email"));
                            sysUser.setMobile(object.getString("mobile"));
                            // 密码默认123456，加密后：MTIzNDU2
                            sysUser.setPassword("MTIzNDU2");
                            // 部门
                            sysUser.setDeptId(deptId);

                            userIds.add(sysUser.getId());

                            // 为承压院用户默认角色
                            //用户角色关联
                            SysUserRole sysUserRole = new SysUserRole();
                            sysUserRole.setRoleId(roleId);
                            sysUserRole.setUserId(sysUser.getId());

                            userRoleList.add(sysUserRole);

                        }
                        insertSysUser(userList);
                        insertSysRole(sysRoleList, userRoleList , userIds);
                    }else{
                        // 没数据，退出同步
                        return false;
                    }
                    if(pageCount == pageIndex){
                        // 最后一页
                        return false;
                    }
                }
            } else {
                return false;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    // 用户新增或编辑
    public void insertSysUser(List<SysUser> userList) {
        SysUserService sysUserService = SpringContextHolder.getBean(SysUserService.class);
        sysUserService.insertOrUpdateBatch(userList);
        System.out.println("用户新增------>>>");
    }

    // 角色新增或编辑
    public void insertSysRole(List<SysRole> roleList, List<SysUserRole> userRoleList , List<String> userIds) {
//        SysRoleService sysRoleService = SpringContextHolder.getBean(SysRoleService.class);
        SysUserRoleService sysUserRoleService = SpringContextHolder.getBean(SysUserRoleService.class);

        // 删除用户对应角色
        Wrapper<SysUserRole> wrapper = new EntityWrapper<SysUserRole>();
        wrapper.in("user_id", userIds);
        sysUserRoleService.delete(wrapper);
        // 新增用户角色
        sysUserRoleService.insertBatch(userRoleList);

    }
}
